package com.jie.server.modules.system.conreoller;


import com.jie.common.component.redis.CaptchaService;
import com.jie.common.component.redis.RedisCache;
import com.jie.common.result.R;
import com.jie.server.common.component.JwtToken;
import com.jie.server.common.domain.LoginUser;
import com.jie.server.modules.system.entity.Menu;
import com.jie.server.modules.system.entity.User;
import com.jie.server.modules.system.service.ILoginService;
import com.jie.server.modules.system.service.IMenuService;
import com.jie.server.modules.system.vo.LoginVo;
import com.jie.server.modules.system.vo.RouterVo;
import com.jie.server.utils.SecurityUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * @description 登录管理 controller控制层
 * @author: xiaojie
 * @since: 2024/12/13 0013
 */
@Api(tags = "登录管理")
@RestController
public class LoginController {

    @Value("${jwt.tokenHead}")
    private String tokenHead;
    @Value(value = "${xl.login.authcode.enable}")
    private boolean needAuthCode;
    @Autowired
    private ILoginService loginService;
    @Autowired
    private IMenuService menuService;
    @Autowired
    private CaptchaService captchaService;
    @Autowired
    private JwtToken jwtToken;
    @Autowired
    private RedisCache redisCache;

    //超时时间定义成两分钟
    public static Long OUT_TIME=2*60*1000L;
    /**
     * 登录
     */
    @ApiOperation(value = "登录")
    @PostMapping(value = "old-login")
    public R login(@RequestBody LoginVo loginVo) {
        // 只有开启了验证码功能才需要验证
        if (needAuthCode) {
            String msg = captchaService.checkImageCode(loginVo.getNonceStr(),loginVo.getValue());
            if (StringUtils.isNotBlank(msg)) {
                return R.error(msg);
            }
        }
        String token = loginService.login(loginVo.getUserName(), loginVo.getPassWord());
        if (StringUtils.isBlank(token)) {
            return R.error("用户名或密码错误");
        }
        Map<String, String> tokenMap = new HashMap<>();
        tokenMap.put("token", token);
        tokenMap.put("tokenHead", tokenHead);
        return R.ok(tokenMap);
    }

    /**
     * 登录后获取用户信息
     */
    @ApiOperation(value = "登录后获取用户信息")
    @GetMapping("get-info")
    public R getInfo() {
        User user = SecurityUtils.getLoginUser().getUser();
        if (user == null) {
            return R.unauthorized();
        }
        // 权限集合
        Set<String> permissions = loginService.getMenuPermission(user);
        // 角色集合
        Set<String> roles = loginService.getRolePermission(user);
        Map<String, Object> data = new HashMap<>();
        data.put("userCode", user.getUserCode());
        data.put("name", user.getRealName());
        data.put("avatar", user.getAvatar());
        data.put("roles", roles);
        data.put("permissions", permissions);
        return R.ok(data);
    }

    /**
     * 登录后获取路由信息
     */
    @ApiOperation(value = "登录后获取路由信息")
    @GetMapping("get-routers")
    public R getRoutes() {
        List<Menu> menus = menuService.selectMenuTreeByUserId(SecurityUtils.getUserId());
        List<RouterVo> routerVos = menuService.buildMenus(menus);
        return R.ok(routerVos);
    }

    /**
     * 登录
     */
    @ApiOperation(value = "登录")
    @PostMapping(value = "login")
    public R newLogin(@RequestBody LoginVo loginVo, HttpSession session) {
        // 只有开启了验证码功能才需要验证
        if (needAuthCode) {

            //打印日志
            System.out.println("用户输入的验证码："+loginVo.getValue());

            //前端返回无效字符串直接返回假
            if(loginVo.getValue() == null || loginVo.getValue() == "") return R.error("验证码不能为空，请填写验证码");

            //校验时间是否过期
            Date before = (Date)session.getAttribute("Time");

            //超时返回假
            if(System.currentTimeMillis() - before.getTime() > OUT_TIME) return R.error("验证码超时了，刷新验证码");;

            //获取正确的验证码
            String code = (String)session.getAttribute("verify_code");

            //比对验证码是否正确（不区分大小写）
            if (loginVo.getValue().equalsIgnoreCase(code)) {
                return R.error("验证码错误，请填写正确的验证码");
            }

        }
        // 用户登录
        LoginUser userInfo = loginService.newLogin(loginVo.getUserName(), loginVo.getPassWord());
        // 原登录账号强退，不允许多地登录
        /*Collection<String> keys = redisCache.keys(CacheConstants.LOGIN_TOKEN_KEY + "*");
        if (CollectionUtil.isNotEmpty(keys)) {
            for (String key : keys) {
                LoginUser onlineUser = redisCache.getCacheObject(key);
                if(onlineUser.getUser().getUserId() != null && onlineUser.getUser().getUserId().equals(userInfo.getUser().getUserId())) {
                    redisCache.deleteObject(key);
                }
            }
        }*/
        Map<String, Object> tokenMap = jwtToken.createToken(userInfo);
        return R.ok(tokenMap);
    }

}
